package org.u2ml.stack.web.spring;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.context.Lifecycle;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

/**
 * This ServletContextListener mimics spring ContextLoaderListener, but starts
 * the context if it implements the lifecycle interface.
 */
public class XContextLoaderListener implements ServletContextListener {

	private ContextLoader contextLoader;
	private WebApplicationContext context;


	/**
	 * Initialize the root web application context.
	 */
	public void contextInitialized(ServletContextEvent event) {
		this.contextLoader = createContextLoader();
		this.context = this.contextLoader.initWebApplicationContext(event.getServletContext());
		if (context instanceof Lifecycle) {
			((Lifecycle) context).start();
		}
	}

	/**
	 * Create the ContextLoader to use. Can be overridden in subclasses.
	 * @return the new ContextLoader
	 */
	protected ContextLoader createContextLoader() {
		return new ContextLoader();
	}

	/**
	 * Return the ContextLoader used by this listener.
	 * @return the current ContextLoader
	 */
	public ContextLoader getContextLoader() {
		return this.contextLoader;
	}


	/**
	 * Close the root web application context.
	 */
	public void contextDestroyed(ServletContextEvent event) {
		if (context instanceof Lifecycle) {
			((Lifecycle) context).stop();
		}
		if (this.contextLoader != null) {
			this.contextLoader.closeWebApplicationContext(event.getServletContext());
		}
	}

	public WebApplicationContext getContext() {
		return context;
	}
}
